<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="ADDdialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色" prop="nickname"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.gender" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
            <el-button v-model="scope.row.id" type="primary" icon="el-icon-edit" size="mini" @click="editFormInfo(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="remoteUserById(scope.row._id)"></el-button>
            <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setDispeachState(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
       </el-pagination>
    </el-card>
        <!-- 添加用户 -->
        <el-dialog
          title="添加用户"
          :visible.sync="ADDdialogVisible"
           width="40%"
           @close="clearAddInfo">
           <!-- 添加信息 -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" >
            <el-form-item label="角色" prop="nickname">
              <el-input v-model="addForm.nickname"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" type="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部按钮 -->
          <span slot="footer" class="dialog-footer">
          <el-button @click="ADDdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户信息 -->
         <el-dialog
          title="修改用户"
          :visible.sync="editdialogVisible"
           width="40%"
           @close="editFormClose"
           >
           <!-- 修改信息 -->

          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" >
            <el-form-item label="角色" prop="nickname">
              <el-input v-model="editForm.nickname" disabled></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" type="password">
              <el-input v-model="editForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
          </el-form>

          <!-- 底部按钮 -->
          <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editPreVaildate">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog
          title="分配权限"
          :visible.sync="addDispeachDialogVisible"
           width="40%">
           <!-- 添加信息 -->
           <div>
             <p>当前用户：{{ userForm.nickname }}</p>
             <p>当前角色：</p>
             <p>分配新角色：
                <el-select v-model="selectRoleId" placeholder="请选择">
                  <el-option v-for="item in allRolesList" :key="item._id" :label="item.roleName" :value="item._id"></el-option>
                </el-select>
             </p>
           </div>
          <!-- 底部按钮 -->
          <span slot="footer" class="dialog-footer">
          <el-button @click="addDispeachDialogVisible = false">取 消</el-button>
          <el-button type="primary" >确 定</el-button>
          </span>
        </el-dialog>
  </div>
</template>
<script>
export default {

  data () {
    var checkEmail = (rule, value, cb) => {
      const regemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regemail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      ADDdialogVisible: false,
      // 添加表单
      addForm: {
        nickname: '',
        password: '',
        email: ''
      },
      // 验证规则
      addFormRules: {
        nickname: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '请输入正确邮箱', trigger: 'blur' }
        ]
      },
      editFormRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 100, message: '请mb5加密字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '请输入正确邮箱', trigger: 'blur' }
        ]
      },
      editdialogVisible: false,
      editForm: {},
      addDispeachDialogVisible: false,
      userForm: [],
      allRolesList: [],
      selectRoleId: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      const res = await this.$http.get('/users', { params: this.queryInfo })
      const req = await this.$http.get('/phoneList')
      console.log(req)
      this.userList = res.data.list
      this.total = res.data.sums
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    handleCurrentChange (newSize) {
      this.queryInfo.pagenum = newSize
      this.getUsersList()
    },
    userStateChange (e) {
      this.$message.success('修改用户状态成功')
    },
    clearAddInfo () {
      this.$refs.addFormRef.resetFields()
    },
    addUsers () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const data = await this.$http.post('/register', this.addForm)
        if (data.status === 201) {
          return this.$message.error('添加用户失败 用户已存在')
        }
        this.$message.success('添加用户成功！')
        this.ADDdialogVisible = false
        this.getUsersList()
      })
    },
    editFormInfo (data) {
      this.editForm = data
      this.editdialogVisible = true
    },
    editFormClose () {
      this.$refs.editFormRef.resetFields()
    },
    editPreVaildate () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入合法字符！')
        await this.$http.put('/register/' + this.editForm._id, {
          email: this.editForm.email
        })
        this.editdialogVisible = false
        this.getUsersList()
        this.$message.success('修改信息成功！')
      })
    },
    async remoteUserById (id) {
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消该操作')
      }
      await this.$http.delete('/users/' + id)
      this.$message.success('删除成功！')
      this.getUsersList()
    },
    async setDispeachState (userInfo) {
      const res = await this.$http.get('/allRoles')
      this.allRolesList = res.data
      this.userForm = userInfo
      this.addDispeachDialogVisible = true
    }
  }
}
</script>
<style lang="less" scoped>
</style>
